package org.cloud.mall.framework.kafka;

import org.cloud.mall.common.constant.KafkaConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * 生产者管理类
 *
 * @ClassName KafkaProducerManager
 * @Description 生产者
 * @Created by zzymaster@163.com 2022/8/2 15:06
 * @Version V1.0
 */
@Component
public class KafkaProducerManager {

    private static final String PUSH_MSG_LOG = "准备发送消息为：{}";

    private static final Logger log = LoggerFactory.getLogger(KafkaProducerManager.class);

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    /**
     * 传入topic名称，消息对象，生产者进行发送
     * @author kevin
     * @param topicName : topic名称
     * @param obj : 消息对象
     * @return boolean : 推送是否成功
     * @date 2021/7/28 15:53
     */
    public boolean sendMessage(String topicName, Object obj) {
        String jsonStr = toJSONString(obj);
        log.info(PUSH_MSG_LOG, jsonStr);
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topicName, jsonStr);

        return dealSendResult(future);
    }

    /**
     * 处理消息推送结果
     * @author kevin
     * @param future :
     * @return boolean
     * @date 2021/7/28 15:56
     */
    private boolean dealSendResult(ListenableFuture<SendResult<String, Object>> future) {
        final boolean[] success = {false};
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
                log.info(KafkaConstants.TOPIC_TEST + " - 生产者 发送消息失败：" + throwable.getMessage());
                success[0] = false;
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //发送成功的处理
                log.info(KafkaConstants.TOPIC_TEST + " - 生产者 发送消息成功：" + stringObjectSendResult.toString());
                success[0] = true;
            }
        });
        return success[0];
    }

}